package cn.itrip.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.userinfo.ItripUserVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.EmptyUtils;
import cn.itrip.common.ErrorCode;
import cn.itrip.common.HttpRequestUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.jar.JarEntry;

@RequestMapping("/api/wx/login")
@Controller
public class WxLoginController {

    @RequestMapping("/wxlogincallback")
    @ResponseBody
    public Dto callBack(String code, String status, HttpServletRequest request) {
        System.out.println("do wx login=======================");

        if (EmptyUtils.isEmpty(code)) {
            System.out.println("删除redis的数据");
            return DtoUtil.returnFail("微信登陆在移动设备上授权失败", ErrorCode.AUTH_AUTHENTICATION_FAILED);
        }

        //用户确认,构建access_token URL,填入所需参数
        StringBuffer requestURL = new StringBuffer("https://api.weixin.qq.com/sns/oauth2/access_token?")
                        .append("appid=wx26e27b54409e8c4c")// 跟第一次请求的一致
                        .append("&secret=26f90c61837491d2b96770ecc03e1ad3")// 查看科泰服务器信息_微信开发对应appid的
                        .append("&code=").append(code)// 第一次请求后得到的参数
                        .append("&grant_type=authorization_code");

        //第二次发送请求:发起access_token请求,得到用户账号信息,转成JSON
        JSONObject jsonObject = HttpRequestUtils.httpGet(requestURL.toString());

        //获取凭证
        String accessToken = jsonObject.getString("access_token");
        String openId =jsonObject.getString("openid");

        System.out.println("accessToken: "+ accessToken +";openId: "+ openId);

        if (EmptyUtils.isEmpty(openId)) {
            return DtoUtil.returnFail("微信登陆异常,请重试", ErrorCode.AUTH_ILLEGAL_USERCODE);
        }


        //准备第三次请求,获取用户信息,--> 使用sns/userInfo
        requestURL =new StringBuffer("https://api.weixin.qq.com/sns/userinfo?")
                .append("access_token=").append(accessToken)
                .append("&openid=").append(openId);

        JSONObject userObject = HttpRequestUtils.httpGet(requestURL.toString());

        String nickName = userObject.getString("nickname");
        String country =userObject.getString("country");

        return DtoUtil.returnDataSuccess("授权登陆成功,nickName: "+nickName+",country: "+country);
    }
}
